<?php

namespace system\model;


use houdunwang\model\Model;
use houdunwang\session\Session;
use houdunwang\validate\build\VaAction;
use houdunwang\validate\Validate;


class  Admin extends model
{

	//数据表
	protected $table ='admin';


	//
   public function login()
   {
	   $data = [
		   'admin_username'=>q('post.admin_username'),
		   'admin_password'=>q('post.admin_password'),
		   'code'=>q('post.code'),
	   ];

	$res = Validate::make([
		//验证用户名  密码
		['admin_username','isnull','用户不能不能为空',self::MUST_VALIDATE],
		['admin_password','isnull','用户密码不能为空',self::MUST_VALIDATE],
		['code','isnull','验证码不能为空',self::MUST_VALIDATE]],$data);

	// 当上面判断为flase
//	   if ($res===false)
//	   {
//	   	return ['valid'=>0,'msg'=>Validate::getError()];
//	   }

	   //比对 用户密码是否正确
	   //2.  比对用户名密码

	   $userInfo = $this->where('admin_username',$data['admin_username'])->first();
	   if (!$userInfo)
	   {
		   return ['valid'=>0,'msg'=>'用户名不正确'];

	   }
	   //校验密码
//	   if(!password_verify($data['admin_password'],$userInfo['admin_password']))
//	   {
//		   return ['valid'=>0,'msg'=>'用户密码不正确'];
//	   }



//	   $userInfo = $this->where('admin_username',$_POST['admin_username'])->where('admin_password',$_POST['admin_password'])->first();

//		dd($userInfo);

	   if (!$userInfo)
	   {

	   	//用户名密码不对
		   return ['valid'=>0,'msg'=>'用户名或者密码不正确'];


	   }
	   if(strtolower(Code::get())!=strtolower($_POST['code']))
	   {
		   return ['valid'=>0,'msg'=>'验证码不正确'];

	   }

		// 对比正确的话 存如 session
	   Session::set('admin.admin_id',$userInfo['admin_id']);
	   Session::set('admin.admin_username',$userInfo['admin_username']);
	   return ['valid'=>1,'msg'=>'登录成功'];

   }


   //修改密码
	public function changePassword($data)
	{
		Validate::make([
		['admin_password','required','请正确原密码',Validate::MUST_VALIDATE],
		['new_password','required','请输入新密码',Validate::MUST_VALIDATE],
		['retry_password','confirm:new_password','两次密码输入一致',Validate::MUST_VALIDATE],
		]);

		//比对原始密码是否正确
		$userInfo = self::find(Session::get('admin.admin_id'));

		echo password_hash("admin888", PASSWORD_DEFAULT);

		if(!password_verify($data['admin_password'],$userInfo['admin_password'])){

			return ['valid'=>0,'message'=>'原始密码不对'];
		}
		//  这里是证明和原始密码比对已经正确  新设置的密码也没问题 所以这里进行 哈希加密 存入数据库
		$userInfo->admin_password = password_hash($data['new_password'],PASSWORD_DEFAULT);
		$userInfo->save();

		// 上面操作完以后 给一个返回值 和成功提示消息
echo 1 ;die;
		return ['valid'=>1,'message'=>'修改成功'];
	}





}














